package app.jppfnetmorph;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;

import netmorph.model.ConfigFile;
import netmorph.model.NetmorphExec;
import neuron.NetworkStatistics;
import neuron.NetworkStatisticsProxy;
import neuron.file.NetmorphLoader;

import org.jppf.server.protocol.JPPFTask;

public class JPPFNetmorphTask extends JPPFTask implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -867876832329654L;

	
	private String netmorphConfig, id;
	private double[] x;
	private int i;
	
	public JPPFNetmorphTask(String config, String id, double[] x, int i) {
		this.netmorphConfig = config;
		this.id = id;
		this.x = x;
		this.i = i;
	}
	
	@Override
	public void run() {
		
		try {
			// init netmorph
			System.out.println("NETMORPH init");
			NetmorphExec rm = new NetmorphExec(new ConfigFile(netmorphConfig), NetmorphExec.DEFAULT_DIRNAME + "-" + id);
			rm.configure(netmorphConfig);
			// run simulation
			System.out.println("NETMORPH run");
			rm.startBG();
			// parse results
			if (rm.getNeurons() == null) { System.out.println("NETMORPH ERROR"); setException(new IOException("NETMORPH RUN ERROR")); return; }
			System.out.println("NETMORPH parse " + rm.getNeurons().getAbsolutePath());
			File neurons = rm.getNeurons();
			NetworkStatistics stats = NetmorphLoader.load(neurons).statistics();
			// copy stats
			System.out.println("NETMORPH copy to proxy");
			NetworkStatisticsProxy proxy = new NetworkStatisticsProxy(stats);
			JobResult result = new JobResult();
			result.stats = proxy;
			result.x = x;
			result.i = i;
			System.out.println("NETMORPH result");
			setResult(result);
			// clean tmp files
			rm.clean();
		} 
		catch (Exception e) {
			System.out.println("NETMORPH exception: " + e.getMessage());
			e.printStackTrace();
			setException(e);
		}
	}
}
